package com.imau.common.utils;


import io.jsonwebtoken.*;
import lombok.Data;

import java.util.Date;
import java.util.Map;

@Data
public class JwtUtil {

    private static String key = "imauhrmaaaaaaaaaaaaaaaaaaaaabbbbbbbbbbbbbbb";

    private static long ttl = 1000 * 60 * 30; //过期时间30分钟


    /**
     * 生成token
     *
     * @param id      用户主键
     * @param subject 用户名
     * @param map     其他信息
     * @return token
     */
    public static  String createJWT(String id, String subject, Map<String, Object> map) {

        //系统当前时间
        long now = System.currentTimeMillis();

        //计算超时时间
        long exp = now + ttl;

        JwtBuilder jwtBuilder = Jwts.builder()
                .setId(id)
                .setSubject(subject)
                .issuedAt(new Date())
                .signWith(SignatureAlgorithm.HS256, key)
                .setClaims(map);

//        for (Map.Entry<String, Object> entry : map.entrySet()) {
//            jwtBuilder.claim(entry.getKey(), entry.getValue());
//        }
        if (ttl > 0) {
            jwtBuilder.expiration(new Date(exp));
        }
        String token = jwtBuilder.compact();

        return token;
    }

    /**
     *
     * @param token 前端值
     * @return  Claims 载荷
     */

    public static  Claims parseJWT(String token) {


        try {
            JwtParserBuilder jwtParserBuilder = Jwts.parser().setSigningKey(key);
            JwtParser build = jwtParserBuilder.build();
            Jws<Claims> claimsJws = build.parseSignedClaims(token);

            Claims claims = claimsJws.getPayload();
            String userId = claims.getId();
            System.out.println(userId);
            return  claims;
        } catch (Exception e)
        {

            System.out.println(e.getMessage());
        }
        return null;
    }

}
